package rpg.client.player.swing.game;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

import rpg.client.Instruction.Type;
import rpg.client.player.swing.GameJPanel;

public class MapJPanel extends JPanel implements KeyListener {
	public static final int TILES_PER_ROW = 7;
	static final int TILE_SIZE_IN_PIXELS = 20;

	/**
     * 
     */
	private static final long serialVersionUID = -8791529379187810733L;

	private final GameJPanel game;

	public MapJPanel(final GameJPanel gameJPanel) {
		super();
		setPreferredSize(new Dimension(TILES_PER_ROW * TILE_SIZE_IN_PIXELS,
				TILES_PER_ROW * TILE_SIZE_IN_PIXELS));
		game = gameJPanel;
		addKeyListener(this);
	}

	@Override
	public void keyPressed(final KeyEvent e) {
	}

	@Override
	public void keyReleased(final KeyEvent e) {
		System.out.println(e);
		switch (e.getKeyCode()) {
		case KeyEvent.VK_C:
			game.character();
			break;
		case KeyEvent.VK_W:
			game.requestMove(Type.MOVE_NORTH);
			break;
		case KeyEvent.VK_A:
			game.requestMove(Type.MOVE_WEST);
			break;
		case KeyEvent.VK_S:
			game.requestMove(Type.MOVE_SOUTH);
			break;
		case KeyEvent.VK_D:
			game.requestMove(Type.MOVE_EAST);
			break;
		default:
			break;
		}
	}

	@Override
	public void keyTyped(final KeyEvent e) {
	}

	@Override
	public void paint(final Graphics g) {
		final char[][] grid = game.getGrid();
		System.out.println("");
		for (final char[] element : grid) {
			System.out.println(new String(element));
		}

		final Graphics2D g2d = (Graphics2D) g;
		for (int y = 0; y < grid.length; y++) {
			for (int x = 0; x < grid[y].length; x++) {
				Color c = Color.BLACK;
				switch (grid[y][x]) {
				case '*':
					c = Color.RED;
					break;
				case 'O':
					c = Color.GREEN;
					break;
				case 'F':
					c = Color.PINK;
					break;
				case 'M':
					c = Color.BLUE;
					break;
				case '.':
					c = Color.WHITE;
					break;
				default:
					c = Color.BLACK;
					break;
				}
				g2d.setPaint(c);
				g2d.fillRect(20 * x, 20 * y, 20, 20);
			}
		}
	}
}
